package cn.combinecalculate.apitest.controller;

import cn.combinecalculate.apitest.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户管理控制器
 * @RestController 组合了@Controller和@ResponseBody
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    private final List<User> users = new ArrayList<>();
    private final AtomicLong counter = new AtomicLong();

    // 初始化一些测试数据
    public UserController() {
        users.add(new User(counter.incrementAndGet(), "张三", "zhangsan@example.com"));
        users.add(new User(counter.incrementAndGet(), "李四", "lisi@example.com"));
    }

    /**
     * 获取所有用户
     * GET /api/users
     */
    @GetMapping
    public List<User> getAllUsers() {
        return users;
    }

    /**
     * 根据ID获取用户
     * GET /api/users/{id}
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return users.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    /**
     * 创建新用户
     * POST /api/users
     */
    @PostMapping
    public User createUser(@RequestBody User user) {
        user.setId(counter.incrementAndGet());
        users.add(user);
        return user;
    }

    /**
     * 更新用户信息
     * PUT /api/users/{id}
     */
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        User user = getUserById(id);
        if (user != null) {
            user.setUsername(userDetails.getUsername());
            user.setEmail(userDetails.getEmail());
        }
        return user;
    }

    /**
     * 删除用户
     * DELETE /api/users/{id}
     */
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        users.removeIf(user -> user.getId().equals(id));
        return "用户删除成功";
    }
}
